#!/usr/bin/env python3
"""
检查HMI原型页面状态的Python脚本
使用Selenium自动化浏览器来检查页面内容
"""

import time
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverException

def setup_driver():
    """设置Chrome浏览器驱动"""
    chrome_options = Options()
    chrome_options.add_argument('--headless')  # 无头模式
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--window-size=1920,1080')
    
    try:
        driver = webdriver.Chrome(options=chrome_options)
        return driver
    except WebDriverException as e:
        print(f"❌ 无法启动Chrome浏览器: {e}")
        print("请确保已安装Chrome浏览器和ChromeDriver")
        return None

def check_page_content(driver, url):
    """检查页面内容"""
    print(f"🌐 正在访问: {url}")
    
    try:
        driver.get(url)
        print("✅ 页面加载成功")
        
        # 等待页面完全加载
        time.sleep(3)
        
        # 检查页面标题
        title = driver.title
        print(f"📄 页面标题: {title}")
        
        # 检查页面源码
        page_source = driver.page_source
        print(f"📊 页面源码长度: {len(page_source)} 字符")
        
        # 检查是否有React应用内容
        react_indicators = [
            "软通动力自动驾驶小巴",
            "启动",
            "登录",
            "硬件检测",
            "网络连接",
            "安全系统",
            "数据获取"
        ]
        
        found_content = []
        for indicator in react_indicators:
            if indicator in page_source:
                found_content.append(indicator)
        
        if found_content:
            print(f"✅ 发现React应用内容: {', '.join(found_content)}")
        else:
            print("❌ 未发现React应用内容")
        
        # 检查控制台错误
        logs = driver.get_log('browser')
        if logs:
            print("🔍 浏览器控制台日志:")
            for log in logs:
                if log['level'] in ['SEVERE', 'ERROR']:
                    print(f"  ❌ {log['level']}: {log['message']}")
                elif log['level'] == 'WARNING':
                    print(f"  ⚠️  {log['level']}: {log['message']}")
                else:
                    print(f"  ℹ️  {log['level']}: {log['message']}")
        else:
            print("✅ 无浏览器控制台错误")
        
        # 检查页面可见元素
        try:
            body = driver.find_element(By.TAG_NAME, "body")
            body_text = body.text.strip()
            if body_text:
                print(f"📝 页面可见文本: {body_text[:200]}...")
            else:
                print("❌ 页面无可见文本内容")
        except Exception as e:
            print(f"❌ 无法获取页面文本: {e}")
        
        # 检查根元素
        try:
            root = driver.find_element(By.ID, "root")
            root_html = root.get_attribute('innerHTML')
            if root_html.strip():
                print(f"🎯 根元素内容长度: {len(root_html)} 字符")
                print(f"🎯 根元素内容预览: {root_html[:200]}...")
            else:
                print("❌ 根元素为空")
        except Exception as e:
            print(f"❌ 无法获取根元素: {e}")
        
        return True
        
    except TimeoutException:
        print("❌ 页面加载超时")
        return False
    except Exception as e:
        print(f"❌ 访问页面时出错: {e}")
        return False

def main():
    """主函数"""
    print("🚀 开始检查HMI原型页面状态...")
    
    # 设置浏览器驱动
    driver = setup_driver()
    if not driver:
        sys.exit(1)
    
    try:
        # 检查页面
        url = "http://localhost:5173"
        success = check_page_content(driver, url)
        
        if success:
            print("\n✅ 页面检查完成")
        else:
            print("\n❌ 页面检查失败")
            
    finally:
        driver.quit()
        print("🔚 浏览器已关闭")

if __name__ == "__main__":
    main()
